package demo4;

public class Main {
    public static void main(String[] args) {
        int[] preorder = {3,9,20,15,7};
        int[] inorder = {9,3,15,20,7};
        Main main = new Main();
        TreeNode treeNode = main.buildTree(preorder, inorder);
    }
    private int k;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        k = 0;
        return buildTreeChild(preorder, k, inorder, 0, inorder.length - 1);
    }
    public TreeNode buildTreeChild(int[] preorder, int indexPre, int[] inorder, int left, int right) {
        if(left > right) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[indexPre]);
        int index = getIndex(preorder, k, inorder, left, right);
        k++;
        root.left = buildTreeChild(preorder, k, inorder, left, index - 1);
        root.right = buildTreeChild(preorder, k, inorder, index + 1, right);

        return root;
    }
    public int getIndex(int[] preorder, int indexPre, int[] inorder, int left, int right) {
        for(int i = left; i <= right; i++) {
            if(inorder[i] == preorder[indexPre]) {
                return i;
            }
        }
        return -1;
    }
}
